import { useEffect, useRef } from 'react'
import { useMemoizedFn } from '@/library/hooks/use-memoized-fn'

export interface NativeType {
  /** 表单元素类型 */
  type: 'checkbox' | 'radio'
  /** 是否选中 */
  checked: boolean
  /** 改变时触发 */
  onChange: (checked: boolean) => void
  /** 是否禁用 */
  disabled?: boolean
  /** 常用于和label配合 */
  id?: string
}

export const NativeInput: React.FC<NativeType> = (props) => {
  const {
    checked,
    disabled,
    id,
    onChange,
    type,
  } = props

  const inputRef = useRef<HTMLInputElement>(null)

  const handleClick = useMemoizedFn((e: MouseEvent) => {
    e.stopPropagation()
    e.stopImmediatePropagation()
    const latestChecked = (e.target as HTMLInputElement).checked
    if (latestChecked === checked) return
    onChange(latestChecked)
  })

  useEffect(() => {
    if (disabled) return undefined
    if (!inputRef.current) return undefined
    const input = inputRef.current
    input.addEventListener('click', handleClick)
    return () => {
      input.removeEventListener('click', handleClick)
    }
  }, [disabled, onChange])

  return (
    <input
      ref={inputRef}
      type={type}
      checked={checked}
      onChange={() => { /* void */ }}
      disabled={disabled}
      id={id}
    />
  )
}
